﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EzDesk.Core.CoreImpl.Repositories.Interface;
using EzDesk.Core.Model;

namespace EzDesk.Core.CoreImpl.Repositories
{
    public class GroupRepository : IGroupRepository, IRepository<Group>
    {        
        private EzDeskDataContext _db;

        public GroupRepository(EzDeskDataContext db)
        {
            this._db = db;
        }

        //todo: 使用DI重构
        public GroupRepository()
            :this(new EzDeskDataContext())
        {}

        #region IRepository<Group> Members

        public void SaveChanges()
        {
            _db.SubmitChanges();
        }

        public Guid Add(Group model, bool saveChanges = true)
        {
            var entity = model.ToEntity();
            _db.ez_Groups.InsertOnSubmit(entity);
            if (saveChanges)
            {
                SaveChanges();
            }
            return entity.GroupId;
        }

        public Group GetById(Guid id)
        {
            Group group = null;
            if (id != null)
            {
                group = _db.ez_Groups.Where(p => p.GroupId == id)
                        .SingleOrDefault()
                        .ToModel();
            }
            return group;
        }

        public IQueryable<Group> GetAll()
        {
            return _db.ez_Groups.Select(
                p => new Group()
                {
                    Id = p.GroupId,
                    Description = p.Description,
                    MemberString = p.MemberString,
                    Type = p.Type,
                }
                );
        }

        public void Delete(Guid id, bool saveChanges = true)
        {
            var entity = _db.ez_Groups.Where(p => p.GroupId == id)
                .SingleOrDefault();
            _db.ez_Groups.DeleteOnSubmit(entity);

            if (saveChanges)
            {
                SaveChanges();
            }
        }

        public void Update(Group model, bool saveChanges = true)
        {
            var entity = _db.ez_Groups.FirstOrDefault(p => p.GroupId == model.Id);
            if (entity != null)
            {
                ModelConvert.CopyValueGroup(entity, model);
            }

            if (saveChanges)
            {
                SaveChanges();
            }
        }

        #endregion
    }
}
